<template>
  <div class="list_url-outer flex">
    <div class="list_url-head flex">
      <div class="list_url-title" v-show="config.title">
        <p>{{config.title}}</p>
      </div>

      <forms :config="search_forms" ref="forms" :inline="true" :class="{hidden:!this.show_search}" :btns="search_btns" >
        <template v-for="(slot, name) in $slots" v-slot:[name]="data">
          <slot :name="name" v-bind="data"></slot>
        </template>
      </forms>

      <div class="list_url-btns flex">
        <el-button @click="show_search = !show_search" v-if="has_search">{{show_search?'收起':'展开'}}搜索</el-button>
        <el-button v-for="row in this_btns" :type="row.type" :size="row.size" @click="row.onclick">{{ row.title }}</el-button>
      </div>

      <slot name="head_extend"></slot>
    </div>

    <TableSlot v-loading="scroll_load_ing" class="max" ref="list" :data="list_data" :cols="config.list_cols" has_select :order="order" :row_class="row_class" :cell_class="cell_class"
               @select:list="selected=$event;selected_ids=selected.map((v)=>{return v.id});" @update:order="order=$event;list()" >
      <template v-for="(slot, name) in $slots" v-slot:[name]="data">
        <slot :name="name" v-bind="data"></slot>
      </template>
    </TableSlot>
<!--    <list v-loading="scroll_load_ing" :scroll_bottom="scroll_load" class="max" ref="list" :data="list_data" :cols="config.list_cols"-->
<!--          :has_select="true" :order="order" :row_class="row_class" :cell_class="cell_class"-->
<!--          @select:list="selected=$event;selected_ids=selected.map((v)=>{return v.id});" @update:order="order=$event;list()" >-->
<!--      <template v-for="(slot, name) in $slots" v-slot:[name]="data">-->
<!--        <slot :name="name" v-bind="data"></slot>-->
<!--      </template>-->
<!--    </list>-->

    <el-pagination v-if="config.limit && !is_scroll" style="padding: 10px;width: 100%;" size="small" :total="page.count" :page-size="page.num" :current-page="page.p" :page-sizes="[20, 50, 100, 300]"
                   :background="false" layout="total, sizes, prev, pager, next, jumper"
                   @update:current-page="page.p=$event;list();" @update:page-size="page.num=$event;page.p=1;list()"
    >
    </el-pagination>

  </div>

</template>
<script>
import {ajax} from "@/js/api_tool.js";
import {decode_btns} from "@/js/s94_tool.js";
import s94Mjs from "s94-js";
import {confirm} from "@/js/tool.js";
import TableSlot from "@/components/slot/TableSlot.vue";

export default {
  name: "list_url",
  components: {TableSlot},
  props: ['config', 'row_class', 'cell_class', 'is_scroll'],
  emits: ['search'],
  data(){
    let is_iframe = !!this.$parent.__iframe;
    let app=this;
    return {
      is_iframe: is_iframe,
      has_search: false,
      // show_search: is_iframe ? false : !!Object.keys(this.config.forms_config).length,
      show_search: false,
      page: {count: 0, num: parseInt(this.config.limit), p: parseInt(this.config.p) || 1},
      list_data: [],
      selected: [],
      selected_ids: [],
      order: this.config.order,
      resdata: typeof(this.config.resdata) == 'function' ? this.config.resdata : function (list){return list;},
      handle_res: typeof(this.config.handle_res) == 'function' ? this.config.handle_res : function (res){return res;},
      search_btns: {
        '重置__small'(){
          app.$refs['forms'].init();
          setTimeout(()=>{app.init();},100)
        },
        '搜索_primary_small'(){ app.search(); },
      },
      scroll_load_ing: false,
      scroll_load_over: false,
    }
  },
  methods:{
    search(){
      this.init();
      this.$emit("search", new FormData(this.$refs['forms'].$el));
    },
    init(){
      this.page.p = 1;
      this.scroll_load_ing = false;
      this.scroll_load_over = false;
      this.list();
    },
    list(data, callback){
      callback = typeof callback === 'function' ? callback : function (){}
      let app = this;
      if (!this.config.api) return;
      let req_url = this.config.api;
      let param = [];
      if(this.config.limit) {
        param.push( (this.config.p_key||'p')+'='+(this.page.p-(this.config.p_start_1?0:1)) );
        param.push( (this.config.n_key||'n')+'='+this.page.num);
      }
      let need_count = !this.page.count && !this.is_scroll;
      if (need_count) {
        param.push( '_need_count_=1');
      }
      if(this.order) {
        let arr = this.order.split(' ');
        param.push('order['+arr[0]+']='+arr[1]);
      }
      let form_dom = this.$refs['forms'].$el;
      if (!form_dom) return;
      let form_data = new FormData(form_dom);
      if (data) param.push(s94Mjs.param_encode(data));
      if (param.length) req_url += (req_url.indexOf('?')==-1?'?':'&')+param.join('&');
      this.scroll_load_ing = true;
      ajax({url:req_url, data:form_data},function(res){
        app.scroll_load_over = res.data.list.length < app.page.num;
        app.scroll_load_ing = false;
        res = app.handle_res(res);
        app.list_data = app.resdata(res.data.list);
        callback(res);
        if (need_count) app.page.count = res.data.count;
        return false
      })
    },
    //批量操作ids
    ids_action(ids, action, callback, op){
      op = op || {};
      let app = this;
      ids = ids || this.selected_ids.join(',');
      if (typeof(ids) != 'string') ids = Object.values(ids).join(',');
      if(!ids) return app.$message.error('所选内容为空');
      let req_url = ~action.indexOf('/') ? action : s94Mjs.dirname(this.config.api)+'/'+action;
      req_url += (~req_url.indexOf('?') ? '&' : '?') + (op.ids_name || 'ids') + '=' + ids;
      let message = op.message;
      if (!message){
        let map = {del:'删除', restore:'恢复', delete: '彻底删除'};
        let action_label = op.action_label || map[action] || "未知";
        message = `是否确定${action_label}选中的数据`;
      }
      confirm(message).then(()=>{
        ajax({url:req_url, data:(op.data || ""), loading:true},function(res){
          if (typeof(callback)!='function' || callback.call(app, res)!==false) {
            app.list();
          }
        })
      }).catch(()=>{})
    },
    //批量删除
    del(ids, callback){
      this.ids_action(ids, 'del', callback)
    },
    //批量恢复
    restore(ids, callback){
      this.ids_action(ids, 'restore', callback)
    },
    //批量彻底删除
    delete(ids, callback){
      this.ids_action(ids, 'delete', callback)
    },
    scroll_load(){
      if (!this.is_scroll) return;
      if (this.scroll_load_over) return ;
      if (this.scroll_load_ing) return;
      let old_list = this.list_data;
      this.list({}, (res)=>{
        this.list_data = old_list.concat(this.list_data);
        this.page.p++;
      })
    }
  },
  watch: {},
  computed: {
    this_btns(){
      return decode_btns(this.config.btns);
    },
    search_forms(){
      let search_forms = this.config.forms_config;
      if (!this.is_iframe) this.show_search = !!Object.keys(search_forms).length;
      let has_search = false;
      Object.values(search_forms).forEach(v=>{
        v.placeholder = v.placeholder || v.tips || '请输入'+v.label;
        if (!v.remove && v.type!="hidden") has_search = true;
      })
      this.has_search = has_search;
      return search_forms;
    },
  },
  mounted(){
    this.init();
  }
}
</script>

<style scoped>
.list_url-outer{flex-direction: column;height: 100%;width: 100%;padding: 10px 20px;background: #fff;border-radius: 8px;}
.list_url-outer .list_url-head{flex-wrap: wrap;width: 100%;}
.list_url-outer .list_url-title{width: auto;padding: 20px 0;}
.list_url-outer .list_url-title p{height: 16px;line-height: 16px;border-left: 04px solid var(--el-color-primary);padding-left: 1em;}
.list_url-outer .list_url-btns{flex-grow: 1;flex-basis: 200px;padding: 10px 0;justify-content: flex-end;flex-wrap: wrap;}
</style>